#include "filehandler.h"

//constructor
file::file(){
    c = (char) NULL;
    eof = true;
    fileName.assign("");
}

//destructor
file::~file(){
    if(file::filestr.is_open()){
        file::filestr.close();
    }
}

/** @fn     file::open()
    @brief  opens the file
    @param  none
    @return 1 upon success
    */
int file::open(){
    //if filename is empty
    if(fileName.empty()){if(DEBUG){cout << "invalid filename \"" << fileName << "\"" << endl;} throw(1);}

    ios_base::openmode fmode;

    if(DEBUG>1){cout << "mode: (";}
    //0001:in
    if(mode == 0x01){fmode |= fstream::in; if(DEBUG>1){cout << "IN";}}
    //0010:out
    if(mode == 0x02){fmode |= fstream::out; if(DEBUG>1){cout << " OUT";}}
    //0100:append
    if(mode == 0x04){fmode |= fstream::app; if(DEBUG>1){cout << " APP";}}
    //1000:trunctate
    if(mode == 0x08){fmode |= fstream::trunc; if(DEBUG>1){cout << " TRUNC";}}
    if(DEBUG>1){cout << ")" << endl;}

    file::filestr.open(fileName.c_str(), fmode);

    eof = filestr.eof();
    return(1);
}

/** @fn     file::close
    @brief  closes the file
    @param  none
    @return void
    */
void file::close(){
    if(file::filestr.is_open()){
        file::filestr.close();
    }
}

/** @fn     file::set(string& strName)
    @brief  sets the filename that the object should open
    @param  strName     the path to the target file
    @return void
    */
void file::set(string& strName){
    fileName.assign(strName);
}

/** @fn     file::getchar()
    @brief  reads a character from the file
    @param  none
    @return the integer value of the read character
    */
int file::getchar(){
    //get characeter and store in c
    c = file::filestr.get();
    //set eof flag if at EOF
    eof = filestr.eof();
    return((int) c);
}

/** @fn     file::putchar(char c)
    @brief  writes a character to a file
    @param  c   the character to be written
    @return return 1 upon success
    */
int file::putchar(char c){
    file::filestr.put(c);
    return(1);
}

/** @fn     file::putstr(char* str)
    @brief  writes a string to a file
    @param  str     pointer to a null-terminated string
    @return 1 upon success
    */
int file::putstr(char* str){
    file::filestr << str << endl;
    return(1);
}

/** @fn     file::state()
    @brief  deternmines wheter a file is successfully opened
    @param  none
    @return true for opened, false if not opened
    */
bool file::state(){
    if(file::filestr.is_open()){
        if(DEBUG){cout << "opened file: " << fileName << endl;}
        return(true);
    }else{
        if(DEBUG){cout << "failed to open file: " << fileName << endl;}
        throw(20);
        return(false);
    }
}
